package com.kittlen.managementSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kittlen.managementSystem.entity.Coach;
import com.kittlen.managementSystem.entity.Evaluate;
import com.kittlen.managementSystem.mapper.EvaluateMapper;
import com.kittlen.managementSystem.service.ICoachService;
import com.kittlen.managementSystem.service.IEvaluateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kittlen
 * @since 2021-02-07
 */
@Service
public class EvaluateServiceImpl extends ServiceImpl<EvaluateMapper, Evaluate> implements IEvaluateService {

    @Resource
    ICoachService iCoachService;

    @Override
    public List<Evaluate> select(Wrapper wrapper) {
        return baseMapper.select(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(Evaluate evaluate) throws Exception{
        try {
            if(baseMapper.insert(evaluate)>0){//添加评论
                UpdateWrapper<Coach> updateWrapper=new UpdateWrapper<Coach>();
                updateWrapper.eq("coach_id",evaluate.getCoach().getCoachId());
                evaluate=baseMapper.selectOne(new QueryWrapper<Evaluate>().select("round(avg(score),1) as score").eq("coach_id",evaluate.getCoach().getCoachId()));//获取平均评价分
                updateWrapper.set("score",evaluate.getScore());
                iCoachService.update(updateWrapper);//修改教练的评分
            }
        }catch (Exception e){
            throw e;
        }
        return 1;
    }
}
